import { getTreelntegration } from "@/api/equipment/position";
export const useModelTree = (type?: string) => {
	/** 树实例 */
	const treeRef = ref<any>();
	/** 树数据 */
	const modelData = ref<any>([]);
	/** 展开的节点的 key 的数组 */
	const defaultExpandedNodes = ref<any>([]);
	/** 根据名称/编码设备位置树搜索 */
	const searchTree = () => {
		getTreeData("", "", false);
	};
	/** 动态加载父级位置树节点 */
	const loadNode = (node: any, resolve: any) => {
		// 一级节点处理
		if (node.level == 0) {
			getTreeData(resolve, "", true);
		}
		// 二级节点处理
		if (node.level >= 1) {
			getTreeData(resolve, node, false);
		}
	};
	/** 获取位置树 */
	const getTreeData = async (resolve: any, node: any, lazeFlag: boolean) => {
		defaultExpandedNodes.value = [];
		if (!lazeFlag && !type) {
			treeRef.value.$refs.treeRef.store.lazy = !treeRef.value?.filterText;
			if (!treeRef.value.$refs.treeRef.store.checkStrictly) {
				treeRef.value.$refs.treeRef.store.checkStrictly = treeRef.value?.filterText;
			}
		}
		let response = await getTreelntegration({
			key: treeRef.value?.filterText,
			upLocationCode: node.data?.nodeCode
		});
		if (node.data?.nodeCode || type == "select") {
			resolve(response.data);
		} else {
			modelData.value = response.data;
			if (treeRef.value?.filterText) {
				pushID(response.data);
			}
		}
	};
	// 递归遍历获取要展开的节点数组
	const pushID = (ids: any) => {
		ids.forEach((item: any) => {
			defaultExpandedNodes.value.push(item.nodeCode);
			if (item.children && item.children.length > 0) {
				pushID(item.children);
			}
		});
	};
	return {
		treeRef,
		modelData,
		defaultExpandedNodes,
		searchTree,
		loadNode
	};
};
